import hashlib
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import check_password

from carts.views import CartView
from user.models import UserProfile
from user.views import make_token


@csrf_exempt
def users_login(request):
    if request.method != "POST":
        return JsonResponse({"code": 405, "error": "Method not allowed"})

    try:
        # 解析请求体
        data = json.loads(request.body)
        print(data)
        username = data.get("username")
        password = data.get("password")

        if not username or not password:
            return JsonResponse({"code": 400, "error": "Username and password are required"})

        try:
            # 查询用户
            user = UserProfile.objects.get(username=username)
        except UserProfile.DoesNotExist:
            return JsonResponse({"code": 404, "error": "User not found"})

        # 验证密码

        if not check_password(password, user.password):
            return JsonResponse({"code": 401, "error": "Invalid credentials"})

        # 生成 token
        token = make_token(username)


        #合并离线购物车和在线购物车和在线
        cart_view = CartView()
        offline_cart = data.get('carts')
        carts_count=cart_view.merge_carts(offline_cart,user)




        result = {
            'code': 200,
            'username': username,
            'data': {'token': token},
            'carts_count': carts_count
        }
        return JsonResponse(result)
    except json.JSONDecodeError:
        return JsonResponse({"code": 400, "error": "Invalid JSON format"})
    except Exception as e:
        return JsonResponse({"code": 500, "error": f"Server error: {str(e)}"})
